<template>
	<view>
		<view class="container" v-if="isPaid">
			<!-- <view class="debug-info" style="
          position: fixed;
          top: 10px;
          left: 10px;
          z-index: 999;
          background: rgba(0, 0, 0, 0.5);
          color: white;
          padding: 10px;
        ">
				<view>当前月份: {{ currentMonth }}</view>
				<view>可用月份: {{ availableMonths.join(",") }}</view>
				<view>当前索引: {{ currentMonthIndex }}</view>
				<view>花朵数量: {{ JSON.stringify(monthFlowers) }}</view>
			</view> -->

			<swiper class="month-swiper" :current="currentMonthIndex" @change="handleMonthChange" :circular="false">
				<swiper-item v-for="(month, index) in availableMonths" :key="month">
					<view class="month-container">
						<image class="maxBac" :src="monthImages[month]" mode="aspectFill" />

						<view class="month-title">{{ month }}月</view>

						<view class="flower-container">
							<block v-for="item in monthFlowers[month] || []" :key="item.id">
								<image 
									:class="[
										'flower',
										item.show ? 'show' : '',
										currentFlower === item.id ? 'moving' : '',
									]"
									:style="{
										opacity: item.opacity,
										left: item.x + '%',
										top: item.y + '%',
									}"
									:src="'../..'+item.imageUrl || '../../static/start1.png'"
									mode="aspectFit"
									:data-id="item.id"
									@touchstart="touchStart"
									@touchmove="touchMove"
									@touchend="touchEnd"
								/>
							</block>
						</view>
					</view>
				</swiper-item>
			</swiper>

			<view :class="['custom-toast', showToast ? 'show' : '']">
				<image class="toast-bg" src="../../static/dialog.png" mode="aspectFit" />
				<view class="toast-content">{{ toastText }}</view>
			</view>

			<view class="page-btns">
				<image 
					class="prev-btn" 
					src="../../static/start1.png" 
					@tap="handlePrevMonth"
					v-show="currentMonthIndex > 0"
				/>
				<image 
					class="next-btn" 
					src="../../static/start1.png" 
					@tap="handleNextMonth"
					v-show="currentMonthIndex < availableMonths.length - 1"
				/>
			</view>
		</view>

		<!-- 支付提示 -->
		<view class="payment-container" v-else>
			<view class="payment-box">
				<view class="payment-title">需要支付才能进入花园</view>
				<view class="payment-amount">￥9.9</view>
				<button class="payment-btn" @click="handlePayment">立即支付</button>
			</view>
		</view>

		<!-- 自定义弹窗 -->
		<view :class="['custom-toast', showToast ? 'show' : '']">
			<image class="toast-bg" src="../../static/dialog.png" mode="aspectFit" />
			<view class="toast-content">{{ toastText }}</view>
		</view>
	</view>
</template>

<script>
	import {
		setUserInfo,
		getUserInfo,
		setToken,
		getToken,
		removeUserInfo,
		removeToken
	} from '@/utils/auth';
	import bgm from '@/utils/bgm'

	export default {
		data() {
			return {
				needPay:true,
				showToast: false,
				isPaid: true,
				currentMonth: new Date().getMonth() + 1,
				// currentMonth: 3,
				availableMonths: [],
				currentMonthIndex: 0,
				monthImages: {},
				monthFlowers: {},
				loading: true,
				showToast: false,
				toastText: '',
				currentFlower: -1,
				moving: false,
				wxuserId: null,
				currentYear:new Date().getFullYear(),
				flowerImages: {},
				specialDates: {} // 存储特殊日期配置
			}
		},

		async onLoad() {
			await this.pay()
			await this.login()
		
			// 初始化并播放背景音乐
			bgm.init()
			bgm.play()
			
			// 检查是否是特殊日期
			this.checkSpecialDate()
		},

		methods: {
			pay() {
				uni.showLoading({
							title: "安全监测中....",
							mask: true
						})
				let that = this
				that.request('config/configKey/pays', '', 'GET').then(res => {
							if (res.code == 200) {
								uni.hideLoading()
								setTimeout(function() {
									uni.hideLoading();
								}, 2000);
								that.needPay=res.msg
							} else {
								uni.showToast({
									icon: "none",
									title: "读取失败！",
									duration: 2000
								})
							}
						})
			},
			login() {
				let that = this
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						let form = {};
						form.code = loginRes.code; //用户code  注:用户的code每次登录都是随机的，所以不需要进行存储
						uni.showLoading({
							title: "登录中....",
							mask: true
						})
						that.request('wxlogin', form, 'POST').then(async wxloginres => {
							console.log("wxloginres: ", wxloginres)
							if (wxloginres.code == 200) {
								uni.hideLoading()
								setTimeout(function() {
									uni.hideLoading();
								}, 2000);
								setToken(wxloginres.data.openid)
								setUserInfo(wxloginres.data); //模拟存储用户信息
								that.wxuserId = wxloginres.data.id
								that.isPaid=wxloginres.data.remark=='true'
								// await that.checkPaymentStatus(wxloginres.data.remark)
								if (that.needPay=='false') {
										that.isPaid=true
									}
									if (that.isPaid&&that.needPay||that.needPay=='false') {
										that.monthFlowers[this.currentMonth] = []
										that.initMonths()

										await that.initGarden()
									}
								
								// that.initMonths()
								// that.initGarden()
							} else {
								uni.showToast({
									icon: "none",
									title: "登录失败，请稍后试试！",
									duration: 2000
								})
							}
						})
					},
					fail(err) {
						console.log(err)
					}
				});
			},
			// 获取用户信息
			// async getUserInfo() {
			// 	try {
			// 		const res = await this.request('info/userInfo', 'GET')
			// 		if (res.code === 200) {
			// 			this.wxuserId = res.data.id
			// 		}
			// 	} catch (error) {
			// 		console.error('获取用户信息失败:', error)
			// 	}
			// },

			showCustomToast(text, duration = 3000) {
				this.showToast = true
				this.toastText = text

				setTimeout(() => {
					this.showToast = false
					this.toastText = ''
				}, duration);
			},
			// 检查支付状态
			// async checkPaymentStatus() {
			// 	try {
			// 		const res = await this.request('info/status', 'GET', {
			// 			wxuserId: this.wxuserId
			// 		})
			// 		// this.isPaid = res.data.paidStatus === 1
			// 	} catch (error) {
			// 		console.error('获取支付状态失败:', error)
			// 	}
			// },

			// 处理支付
			async handlePayment() {
				try {
					const res = await this.request('pay/jsapiPay', {
						wxuserId: this.wxuserId,
						
					}, 'POST')
					// 调用微信支付
					uni.requestPayment({
						...res.data,
						success: () => {
							this.isPaid = true
							this.initGarden()
						},
						fail: (err) => {
							console.error('支付失败:', err)
							uni.showToast({
								title: '支付失败',
								icon: 'none'
							})
						}
					})
				} catch (error) {
					console.error('创建支付订单失败:', error)
				}
			},

			// 初始化可用月份
			initMonths() {
				const currentMonth = this.currentMonth
				this.availableMonths = Array.from({
					length: currentMonth
				}, (_, i) => i + 1)
				this.currentMonthIndex = this.availableMonths.length - 1

				// 为每个月份初始化一个空数组
				this.availableMonths.forEach(month => {
					this.$set(this.monthFlowers, month, [])
				})

				console.log('可用月份：', this.availableMonths)
				console.log('当前月份索引：', this.currentMonthIndex)
			},

			async initFlowerImages() {
				try {
					const res = await this.request('flowerimage/list', {
						pageNo: 1,
						pageSize: 10000,
						year: this.currentYear
					}, 'GET')
					
					if (res.code === 200) {
						this.flowerImages = res.rows.reduce((acc, curr) => {
							const days = curr.days.split(',').map(d => parseInt(d))
							if (!acc[curr.year]) acc[curr.year] = {}
							if (!acc[curr.year][curr.month]) acc[curr.year][curr.month] = {}
							
							days.forEach(day => {
								acc[curr.year][curr.month][day] = curr.imageUrl
							})
							return acc
						}, {})
						
						console.log('花朵图片配置:', this.flowerImages)
					}
				} catch (error) {
					console.error('加载花朵图片配置失败:', error)
				}
			},

			async initGarden() {
				await this.initFlowerImages()
				let form = {
					pageNo: 1,
					pageSize: 10000
				}
				try {
					const res = await this.request('image/list', form, 'GET')
					if (res.code === 200) {
						// 转换图片数据格式
						this.monthImages = res.rows.reduce((acc, curr) => {
							acc[curr.month] = curr.imageUrl // 注意：这里移除了 this.myimgurl() 因为后端返回的应该是完整URL
							return acc
						}, {})
						console.log('月份图片：', this.monthImages)
						// 加载当前月份的花朵数据
						await this.loadMonthFlowers(this.currentMonth)
					}
					this.loading = false
				} catch (error) {
					console.error('初始化花园失败:', error)
					uni.showToast({
						title: '初始化失败，请重试',
						icon: 'none'
					})
				}
			},

			// 加载指定月份的花朵数据
			async loadMonthFlowers(month) {
				try {
					const res = await this.request('flower/list', {
						pageNo: 1,
						pageSize: 10000,
						wxuserId: this.wxuserId,
						month: month
					}, 'GET')
					
					console.log('完整的返回数据:', res)
					console.log('rows数据:', res.rows)
					console.log('当前月份:', month)
					console.log('monthFlowers之前:', this.monthFlowers)
					
					if (res.code === 200 && res.rows && res.rows.length > 0) {
						const data = res.rows[0];  // 获取包含所有信息的对象
						
						// 设置花朵数据，添加图片URL
						this.$set(this.monthFlowers, month, data.flowers.map(flower => ({
							id: flower.id,
							show: true,
							opacity: 1,
							x: Number(flower.xPosition),
							y: Number(flower.yPosition),
							canMove: this.canMoveFlower(!!flower.updateTime?flower.updateTime:flower.createTime),
							number: flower.day,
							imageUrl: this.getFlowerImage(month, flower.day) // 获取对应的花朵图片
						})))

						// 显示新增花朵信息
						if (data.totalNewFlowers > 0) {
							let message = `解锁了${data.totalNewFlowers}朵新花！\n`;
							data.newFlowersByMonth.forEach(item => {
								message += `${item.month}月: ${item.count}朵\n`;
							});
							this.showCustomToast(message);
						}
					}

					uni.hideLoading()
				} catch (error) {
					console.error('加载月份数据失败:', error)
					uni.hideLoading()
				}
			},

			// 检查花朵是否可以移动
			canMoveFlower(lastMoveTime) {
				if (!lastMoveTime) return true
				const hours = (new Date() - new Date(lastMoveTime)) / (1000 * 60 * 60)
				return hours <= 24
			},

			// 处理月份切换
			async handleMonthChange(e) {
				const index = e.detail.current
				const month = this.availableMonths[index]

				if (!this.monthFlowers[month]) {
					await this.loadMonthFlowers(month)
				}
			},

			// 更新花朵位置 - 只更新本地状态
			touchMove(e) {
				if (!this.moving || this.loading) return

				const id = this.currentFlower
				const currentMonth = this.availableMonths[this.currentMonthIndex]
				const flower = this.monthFlowers[currentMonth].find(f => f.id === id)
				if (!flower || !flower.canMove) return

				const touch = e.touches[0]
				const x = (touch.clientX / uni.getSystemInfoSync().windowWidth) * 100
				const y = (touch.clientY / uni.getSystemInfoSync().windowHeight) * 100

				// 只更新本地数据
				this.monthFlowers[currentMonth] = this.monthFlowers[currentMonth].map(f => {
					if (f.id === id) {
						return {
							...f,
							x,
							y
						}
					}
					return f
				})
			},

			touchStart(e) {
				if (this.loading) return
				const id = e.currentTarget.dataset.id
				const currentMonth = this.availableMonths[this.currentMonthIndex]
				const flower = this.monthFlowers[currentMonth]?.find(f => f.id === id)
				if (!flower || !flower.canMove) return

				this.moving = true
				this.currentFlower = id
			},

			async touchEnd() {
				if (this.loading) return

				// 如果正在移动花朵
				if (this.moving && this.currentFlower !== -1) {
					const currentMonth = this.availableMonths[this.currentMonthIndex]
					const flower = this.monthFlowers[currentMonth].find(f => f.id === this.currentFlower)

					if (flower) {
						try {
							// 拖动结束时才发送请求更新位置
							await this.request('flower', {
								id: this.currentFlower,
								xPosition: flower.x.toFixed(2),
								yPosition: flower.y.toFixed(2)
							}, 'PUT')
						} catch (error) {
							console.error('更新花朵位置失败:', error)
							// 如果更新失败，可以选择是否要回滚位置
							uni.showToast({
								title: '位置更新失败',
								icon: 'none'
							})
						}
					}
				}

				// 重置状态
				this.moving = false
				this.currentFlower = -1
			},

			// 处理上一月
			handlePrevMonth() {
				if (this.currentMonthIndex > 0) {
					this.currentMonthIndex--
				}
			},
			
			// 处理下一月
			handleNextMonth() {
				if (this.currentMonthIndex < this.availableMonths.length - 1) {
					this.currentMonthIndex++
				}
			},
			
			// 初始化特殊日期配置
			async initSpecialDates() {
				try {
					const res = await this.request('date/list', {
						pageNo: 1,
						pageSize: 10000,
						year: this.currentYear
					}, 'GET')
					
					if (res.code === 200) {
						// 转换为易于查找的格式
						this.specialDates = res.rows.reduce((acc, curr) => {
							const key = `${curr.year}-${curr.month}-${curr.day}`
							acc[key] = curr.message
							return acc
						}, {})
						
						console.log('特殊日期配置:', this.specialDates)
					}
				} catch (error) {
					console.error('加载特殊日期配置失败:', error)
				}
			},

			// 修改检查特殊日期的方法
			async checkSpecialDate() {
				if (Object.keys(this.specialDates).length === 0) {
					await this.initSpecialDates()
				}

				const today = new Date()
				const year = today.getFullYear()
				const month = today.getMonth() + 1
				const date = today.getDate()
				
				const key = `${year}-${month}-${date}`
				if (this.specialDates[key]) {
					this.showCustomToast(this.specialDates[key])
				}
			},

			getFlowerImage(month, day) {
				return this.flowerImages[this.currentYear]?.[month]?.[day] || '../../static/start1.png'
			}
		}
	}
</script>

<style lang="scss">
	.container {
		width: 100%;
		height: 100vh;
		position: relative;
	}

	.maxBac {
		width: 100%;
		height: 100%;
		position: absolute;
		z-index: 1;
	}

	.flower-container {
		width: 100%;
		height: 100%;
		position: relative;
		z-index: 2;
	}

	.flower {
		width: 100rpx;
		height: 100rpx;
		position: absolute;
		transition: all 0.3s;
		opacity: 0;
		transform: scale(0);

		&.show {
			opacity: 1;
			transform: scale(1);
		}

		&.moving {
			transform: scale(1.2);
		}
	}

	.custom-toast {
		position: fixed;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		z-index: 999;
		opacity: 0;
		transition: opacity 0.3s;
		pointer-events: none;

		&.show {
			opacity: 1;
		}
	}

	.toast-bg {
		width: 600rpx;
		height: 300rpx;
	}

	.toast-content {
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		color: #333;
		font-size: 32rpx;
		text-align: center;
		white-space: pre-line;
	}

	.payment-container {
		width: 100%;
		height: 100vh;
		display: flex;
		align-items: center;
		justify-content: center;
		background: #f5f5f5;
	}

	.payment-box {
		background: #fff;
		padding: 40rpx;
		border-radius: 20rpx;
		text-align: center;
	}

	.payment-title {
		font-size: 32rpx;
		margin-bottom: 30rpx;
	}

	.payment-amount {
		font-size: 48rpx;
		color: #ff6b6b;
		margin-bottom: 30rpx;
	}

	.payment-btn {
		background: #ff6b6b;
		color: #fff;
		border: none;
		padding: 20rpx 60rpx;
		border-radius: 100rpx;
	}

	.month-swiper {
		width: 100%;
		height: 100vh;
	}

	.month-container {
		width: 100%;
		height: 100%;
		position: relative;
	}

	.month-title {
		position: absolute;
		top: 40rpx;
		left: 40rpx;
		z-index: 3;
		font-size: 36rpx;
		color: #fff;
		text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
	}

	.page-btns {
		position: fixed;
		bottom: 40rpx;
		left: 0;
		width: 100%;
		display: flex;
		justify-content: space-between;
		padding: 0 40rpx;
		z-index: 10;
		
		.prev-btn,
		.next-btn {
			width: 80rpx;
			height: 80rpx;
			opacity: 0.6;
			
			&:active {
				opacity: 1;
			}
		}
	}

	// 添加翻页动画
	.month-swiper {
		.uni-swiper-slide-transition {
			transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
			
			&.uni-swiper-slide-next {
				transform: translate3d(100%, 0, 0) !important;
			}
			
			&.uni-swiper-slide-prev {
				transform: translate3d(-100%, 0, 0) !important;
			}
		}
	}
</style>